using System;
using System.Collections;
using System.Reflection;
using DeploymentWang.Interfaces.Entities;
using LinqToExcel;

namespace DeploymentWang.Core.Readers
{
    public abstract class ExcelReaderBase<T> where T: class
    {
        protected string mySpreadsheetFilename;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:System.Object"/> class.
        /// </summary>
        protected ExcelReaderBase(string spreadsheetFilename)
        {
            mySpreadsheetFilename = spreadsheetFilename;
        }

        protected virtual IEnumerable GetData(string worksheetName)
        {
            var builder = new LinqToExcelEntityBuilder<T>(AssemblyResolver);
            var configSetting = builder.Build(worksheetName);
            var provider = ExcelProvider.Create(mySpreadsheetFilename);
            var gmi = typeof(ExcelProvider).GetMethod("GetSheet").MakeGenericMethod(configSetting.GetType());
            return (IEnumerable) gmi.Invoke(provider, null);            
        }

        public static Assembly AssemblyResolver(ResolveEventArgs args)
        {
            if (args.Name.StartsWith("DeploymentWang.Interfaces"))
                return typeof(ConfigSetting).Assembly;

            return null;
        }
        
    }
}